<template>
    <van-nav-bar
    title="商品直播"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
    />
    <van-barrage class="box" style="position: relative;" v-model="barrageList" :rows="10">
        <div class="prism-player" id="live"></div>
    </van-barrage>
    <van-form @submit="LaunchBarrage">
        <van-cell-group inset>
            <van-field v-model="barrage" label="弹幕" placeholder="请输入弹幕">
                <template #button>
                    <van-space>
                        <van-button size="small" type="primary" native-type="submit">发送</van-button>
                        <van-button icon="cart-o" type="primary" size="small" @click="show=true" />
                    </van-space>
                </template>
            </van-field>
        </van-cell-group>
    </van-form>
    <van-popup
    v-model:show="show"
    closeable
    close-icon="close"
    position="bottom"
    :style="{ height: '50%' }"
    z-index="999"
    >
        <template #default>
            <van-nav-bar title="直播商品"/>
            <van-card
            :tag="liveProduct.relation_object.flag_text"
            :price="liveProduct.price"
            :desc="liveProduct.stock"
            :title="liveProduct.relation_object.name"
            :thumb="liveProduct.relation_object.thumbs_text"
            :origin-price="liveProduct.relation_object.price"
            v-for="liveProduct in list"
            :key="liveProduct.id"
            >
            <template #desc>
                <van-highlight :keywords="`${liveProduct.stock}`" :source-string="`剩余数量：${liveProduct.stock}${liveProduct.relation_object.unit_text}`" />
            </template>
            <template #num>
                <van-button size="mini" @click="addSku(liveProduct)">立即购买</van-button>
            </template>
            </van-card>
        </template>
    </van-popup>
    <van-sku
      v-model="SkuShow"
      :sku="sku"
      :initial-sku="initialSku"
      :goods="goods"
      :goods-id="id"
      :properties="properties"
      :quota="quota"
      :show-add-cart-btn="false"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
    >
    <template #sku-stepper>
      <div class="detailbox stepper">
        <span>购买数量：</span>
        <van-stepper v-model="nums" :max="sku.stock_num" :min="1"/>
      </div>
    </template>
    </van-sku>
</template>

<script setup>
    import  '/public/assets/plugin/ckplayer/js/ckplayer';
    const {proxy} = getCurrentInstance()
    const onClickLeft = ()=>proxy.$router.go(-1)
    const show = ref(false)
    const list = ref([])
    let isLogin = ref(proxy.$business.value.id != 0)
    onMounted(async()=>{
        let result = await proxy.$GET({url:'/live'})
        if(!result.code){
            showFailToast({
                message: result.msg,
                onClose: () => proxy.$router.go(-1)
            })
        }
        list.value = result.data
        var videoObject = {
            container: '#live',
            live:true,//指定为直播
            plug:'hls.js',//使用hls.js插件播放m3u8
            video: result.msg,
            autoplay: true,//是否自动播放
            loop: true,//是否需要循环播放
            ended:null,//结束显示的内容
            logo:'',//logo
        }
        new ckplayer(videoObject)
        //登录状态
        if(!isLogin.value){
            const token = localStorage.getItem('token')
            if(token){
                const result = await proxy.$GET({
                    url:'/business/check',
                    params:{token}
                })
                if(result.code==0){
                isLogin.value = false
                }else{
                proxy.$business.value = result.data;
                isLogin.value = true
                }
            }else{
            isLogin.value = false
            }
        }
    })
    const barrage = ref('')
    const barrageList = ref([]);
    const LaunchBarrage = () => {
      barrageList.value.push({ id: Math.random(), text: barrage.value });
      barrage.value = ''
    };
    //规格
    import VanSku from 'vant-sku';
    import 'vant-sku/dist/index.css'
    //初始化
    const id = ref(0)
    const SkuShow = ref(false)
    const sku = ref({})
    const properties = ref([])
    const quota = ref(0);
    const goods = ref({})
    const initialSku = reactive({
        // 初始选中的商品属性
        // 键：属性id
        // 值：属性值id列表
        selectedProp: {}
    })
    //规格选择
    const addSku = async(liveProduct)=>{
        if(!isLogin.value){
            showFailToast({
                message: '未登录',
                duration: 1000,
                onClose: () => proxy.$router.push({path:'/business/login',query:{path:'/live'}})
            })
            return
        }
        liveProductId.value = liveProduct.id
        let product = liveProduct.relation_object
        if(id.value == product.id){
            SkuShow.value = true
            return
        }
        id.value = product.id
        goods.value = {
            picture: product.thumbs_text,
        }
        sku.value = {
            tree: [],
            list: [],
            price: liveProduct.price, // 默认价格（单位元）
            stock_num: liveProduct.stock, // 商品总库存
        }
        properties.value = []
        let result = await proxy.$GET({
            url:'/product/prop',
            params:{id:product.id}
        })
        result.forEach(e => {
            let isinclude = false
            properties.value.forEach(p => {
                if(p.k_id==e.propid){
                    isinclude = true
                    p.v.push({
                        id: e.id, // 属性值id
                        name: e.value, // 属性值名
                        price: parseFloat(e.price)*100, // 属性值加价
                        text_status: 1, // 属性启用/禁用状态 0 - 禁用，1 - 启用
                    })
                    return
                }
            })
            if(!isinclude){
                properties.value.push({
                    k_id: e.propid, // 属性id
                    k: e.prop_text, // 属性名
                    is_multiple: false, // 是否可多选
                    v: [{
                        id: e.id, // 属性值id
                        name: e.value, // 属性值名
                        price: parseFloat(e.price)*100, // 属性值加价
                        text_status: 1, // 属性启用/禁用状态 0 - 禁用，1 - 启用
                    }],
                })
                sku.value.list.push({
                    s1 : e.propid,
                    price : parseFloat(liveProduct.price)*100, //默认的商品价格
                    stock_num : liveProduct.stock,
                })
                initialSku.selectedProp[e.propid] = [e.id]
            }
        })
        SkuShow.value = true
    }
    //添加购物车
    const nums = ref(1)
    let onAddCartClicked = async (skuData)=>{
        let skuComb = skuData.selectedSkuComb
        if(skuComb){
            let result = await proxy.$PUT({
            url:'/product/cart',
            params:{id:id.value},
            data:{
                nums:nums.value,
                price:(skuComb.property_price+skuComb.price)/100,
                attrs:JSON.stringify(skuComb.properties.map(p=>p.v[0].id))
            }
            })
            if(result){
            SkuShow.value = false
            showSuccessToast({
                message: result.msg,
                duration: 1000,
            })
            }else{
            SkuShow.value = false
            showFailToast({
                message: result.msg,
                duration: 1000,
            })
            }
        }else{
            showFailToast({
            message: '请选择商品规格',
            duration: 1000,
            })
        }
    }
    //购买
    const liveProductId = ref(0)
    let onBuyClicked = async (skuData)=>{
        let skuComb = skuData.selectedSkuComb
        proxy.$router.push({path:`/cart/confirm`,query:{
            type:'live',
            id:liveProductId.value,
            nums:nums.value,
            attrs:JSON.stringify(skuComb.properties.map(p=>p.v[0].id))
        }})
    }
</script>

<style src="/public/assets/plugin/ckplayer/css/ckplayer.css"></style>
<style src="/public/assets/css/live.css"></style>